package com.whut.googleplay.protocol;

import android.os.SystemClock;

import com.whut.googleplay.global.Config;
import com.whut.googleplay.http.HttpHelper;
import com.whut.googleplay.http.HttpResult;
import com.whut.googleplay.utils.FileUtils;
import com.whut.googleplay.utils.IOUtils;
import com.whut.googleplay.utils.StringUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * ============================================================
 * <br/>
 * 作 者 :        xyb
 * <br/>
 * 版 本 :        1.0
 * <br/>
 * 创建日期 ：     2016-05-04 下午5:55
 * <br/>
 * 描 述 ： baseProtocol协议，目前提供1抽象方法供实现 <br/>
 * 1.parseFromJson 针对不同的json进行具体的解析
 * <br/>
 * 修订历史 ：
 * <br/>
 * ============================================================
 **/
public abstract class BaseProtocol<Data> {

    public abstract Data parseFromJson(String json);

    //返回该协议的地址
    public abstract String getKey();

    public Data load(int index) {
        SystemClock.sleep(1000);// 休息1秒，防止加载过快，看不到界面变化效果
        String json = null;
        json = loadFromLocal(index);
        if (StringUtils.isEmpty(json)) {
            json = loadFromNet();
            if (StringUtils.isEmpty(json)) {
                return null;
            } else {
                saveToLocal(json, index);
            }
        }
        return parseFromJson(json);
    }

    /**
     * 从网络层加载
     *
     * @return
     */
    private String loadFromNet() {
        String json = null;
        HttpResult httpResult = HttpHelper.get(Config.POSTMAN_ROOT_URL, true);
        if (httpResult != null) {
            json = httpResult.getString();
        }
        return json;
    }

    /**
     * 保存至本地
     *
     * @param saveStr 要保存的字符串
     * @param index   保存的index
     */
    private void saveToLocal(String saveStr, int index) {

        BufferedWriter bufferWrite = null;
        if (!StringUtils.isEmpty(saveStr)) {
            try {
                String path = FileUtils.getCachePath();
                bufferWrite = new BufferedWriter(new FileWriter(path + getKey() + "_" + index));
                long time = System.currentTimeMillis() + 1000 * 60;
                bufferWrite.write(time + "\r\n");
                bufferWrite.write(saveStr);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.close(bufferWrite);
            }
        }
    }

    /**
     * 从本地加载
     *
     * @return
     */
    private String loadFromLocal(int index) {
        String json = null;
        BufferedReader bufferedReader = null;
        try {
            String path = FileUtils.getCachePath();
            bufferedReader = new BufferedReader(new FileReader(path + getKey() + "_" + index));
            String line = bufferedReader.readLine();
            Long time = Long.valueOf(line);
            //表示当前还没过期
            if (time > System.currentTimeMillis()) {
                StringBuffer stringBuffer = new StringBuffer();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    stringBuffer.append(temp);
                }
                json = stringBuffer.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(bufferedReader);
        }
        return json;
    }
}
